package com.java.computeronline.model.blo;

import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.java.computeronline.model.entity.Manufacturer;
import com.java.computeronline.model.entity.Supplier;

public class SupplierBLO {
	@SuppressWarnings("unchecked")
	public List<Supplier> list(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Supplier> suppliers = null;
		Query query = pm.newQuery(Supplier.class);
		suppliers = (List<Supplier>)query.execute();
		return suppliers;
	}
	
	public Supplier getById(Long id){
		Supplier supplier = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			supplier = pm.getObjectById(Supplier.class, id);
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			pm.close();
		}
		return supplier;
	}
	
	
	public Supplier add(Supplier supplier) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
            pm.makePersistent(supplier);
        }catch(Exception ex){
        	ex.printStackTrace();
        } finally {
            pm.close();
        }
		return supplier;
	}
	
	public Supplier delete(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Supplier supplier;
		try {
			pm.currentTransaction().begin();
			supplier = pm.getObjectById(Supplier.class, id);
            pm.deletePersistent(supplier);
            pm.currentTransaction().commit();
        }catch(Exception ex){
        	pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
        } finally {
            pm.close();
        }
		return supplier;
	}
	
	public Supplier update(Supplier sup){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Supplier supplier;
		try {
			pm.currentTransaction().begin();
			supplier = pm.getObjectById(Supplier.class, sup.getId());
			supplier.setAddress(sup.getAddress());
			supplier.setEmail(sup.getEmail());
			supplier.setName(sup.getName());
			supplier.setPhone(sup.getPhone());
            pm.makePersistent(supplier);
			pm.currentTransaction().commit();
        }catch(Exception ex){
        	pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
        } finally {
            pm.close();
        }
		return supplier;
	}
}
